<?php

namespace App\Services\Admin;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Log;
use App\Models\Permission;

class PermissionService extends AdminService{

    /**
     * 创建权限
     * @param [type] $data
     * @method createPermission
     * @author chengzhigang<1256699215@qq.com>
     * @param
     * @return
     */
    public function createPermission($data){
        try{
            $res = Permission::create($data);
            if($res){
                return ['status' => 1, 'msg' => '提交成功', 'data' => []];
            }else{
                return ['status' => 2, 'msg' => '提交失败', 'data' => []];
            }
        }catch(\Exception $e){
            Log::info($e->getCode());
            Log::info($e->getFile());
            Log::info($e->getLine());
            Log::info('创建权限：' . $e->getMessage());
            writeErrorLog($e);
            return ['status' => 2, 'msg' => config('const.error'), 'data' => []];
        }
    }

    /**
     * 更新权限
     * @param [type] $id
     * @param [type] $data
     * @method updatePermission
     * @author chengzhigang<1256699215@qq.com>
     * @param
     * @return
     */
    public function updatePermission($id,$data){
        try{
            $permission = Permission::find($id);
            if(empty($permission)){
                return ['status' => 2, 'msg' => '更新失败', 'data' => []];
            }
            if ($permission->update($data)){
                return ['status' => 1, 'msg' => '更新成功', 'data' => []];
            }else{
                return ['status' => 2, 'msg' => '更新失败', 'data' => []];
            }
        }catch(\Exception $e){
            Log::info($e->getCode());
            Log::info($e->getFile());
            Log::info($e->getLine());
            Log::info('更新权限：' . $e->getMessage());
            writeErrorLog($e);
            return ['status' => 2, 'msg' => config('const.error'), 'data' => []];
        }
    }

    /**
     * 获取列表
     * @param [type] $parent_id
     * @param [type] $page
     * @param [type] $per_page
     * @method getList
     * @author chengzhigang<1256699215@qq.com>
     */
    public function getList($parent_id,$page,$per_page){
        try{
            $data = Permission::where('parent_id', $parent_id)->orderBy('sort','desc')->paginate($per_page,['*'],'page',$page)->toArray();
            return ['status'=>1,'msg'=>'请求成功','data'=>$data];
        }catch(\Exception $e){
            Log::info($e->getCode());
            Log::info($e->getFile());
            Log::info($e->getLine());
            Log::info('权限列表：' . $e->getMessage());
            writeErrorLog($e);
            return ['status' => 2, 'msg' => config('const.error'), 'data' => []];
        }
    }
}
